package cn.nfwx.tv.fragment.me;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import cn.nfwx.tv.R;
import cn.nfwx.tv.base.BaseFragment;
import cn.nfwx.tv.controller.DownloadM3u8Controller;
import cn.nfwx.tv.controller.me.MineAppointmentController;
import cn.nfwx.tv.controller.me.MineSubscriptionController;
import cn.nfwx.tv.controller.me.MineTvDownloadController;
import cn.nfwx.tv.controller.me.MineTvHistroyController;
import cn.nfwx.tv.db.DownProgramModel;
import cn.nfwx.tv.down.DownloadConstant;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.util.RecyclerViewUtil;
import cn.nfwx.tv.widget.LoadView;
import cn.nfwx.tv.widget.WxLoadmoreView;
import cn.nfwx.tv.widget.WxRefreshView;

public class MineAllFragment extends BaseFragment implements OnTabSelectListener, View.OnClickListener {
    private SegmentTabLayout sub_segment_tab;
    private String[] downloadTitles = {"正在下载", "已下载"};
    private TwinklingRefreshLayout trl_mine;
    private RecyclerView rl_mine;
    private TextView edit_mine_btn;

    private LinearLayout ll_mine_pause, ll_mine_bottom;
    private View v_spilt_pause, v_spilt_bottom;
    private View notDataView;
    private ImageView empty_image, btn_all;
    private TextView empty_text, all_text;
    private LoadView loadView;
    private TextView tv_mine_select, tv_mine_delete;
    private HorizontalDividerItemDecoration itemDecoration;

    private static final String POSITION_KEY = "POSITION_KEY";
    private int index;
    private BroadcastReceiver downloadReceiver;

    /**
     * =====订阅变量=====
     */
    private String[] subscriptionTitles = {"我的订阅", "热门节目"};
    private MineSubscriptionController mineSubscriptionController;
    private int currentSubTabSelect;

    /**
     * =====观看记录=====
     */
    private MineTvHistroyController mineTvHistroyController;

    /**
     * =====预约记录=====
     */
    private MineAppointmentController mineAppointmentController;

    /**
     * =====我的下载=====
     */
    private MineTvDownloadController mineTvDownloadController;

    public static MineAllFragment newInstance(int index) {
        MineAllFragment fragment = new MineAllFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(POSITION_KEY, index);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View initView() {
        View view = View.inflate(getActivity(), R.layout.fragment_subscript, null);
        sub_segment_tab = findView(view, R.id.sub_segment_tab);

        trl_mine = findView(view, R.id.trl_mine);
        WxRefreshView sinaRefreshView = new WxRefreshView(getContext());
        sinaRefreshView.setArrowResource(R.mipmap.mine_down);
        trl_mine.setHeaderView(sinaRefreshView);
        trl_mine.setBottomView(new WxLoadmoreView(getContext()));
        trl_mine.setOnRefreshListener(refreshListener);

        rl_mine = findView(view, R.id.rl_mine);
        RecyclerViewUtil.setLinearLayoutManagerWithoutDivder(mContext, rl_mine);
        rl_mine.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(mContext).resumeRequests();
                } else {
                    Glide.with(mContext).pauseRequests();
                }
            }
        });

        edit_mine_btn = findView(view, R.id.edit_mine_btn);

        ll_mine_pause = findView(view, R.id.ll_mine_pause);
        v_spilt_pause = findView(view, R.id.v_spilt_pause);
        btn_all = findView(ll_mine_pause, R.id.btn_all);
        all_text = findView(ll_mine_pause, R.id.all_text);


        v_spilt_bottom = findView(view, R.id.v_spilt_bottom);
        ll_mine_bottom = findView(view, R.id.ll_mine_bottom);

        notDataView = LayoutInflater.from(mContext).inflate(R.layout.view_nodata, (ViewGroup) rl_mine.getParent(), false);
        empty_image = findView(notDataView, R.id.empty_image);
        empty_text = findView(notDataView, R.id.empty_text);

        loadView = new LoadView(mContext);
        loadView.setOnLoadClickLisener(new LoadView.OnLoadClickListener() {
            @Override
            public void onreload() {
                refresh();
            }

            @Override
            public void onnext() {

            }
        });
        tv_mine_select = findView(view, R.id.tv_mine_select);
        tv_mine_delete = findView(view, R.id.tv_mine_delete);


        tv_mine_select.setOnClickListener(this);
        tv_mine_delete.setOnClickListener(this);
        edit_mine_btn.setOnClickListener(this);

        itemDecoration = new HorizontalDividerItemDecoration.Builder(mContext).size(10).build();

        if (downloadReceiver == null) {
            downloadReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (null != intent) {
                        switch (intent.getAction()) {
                            case DownloadM3u8Controller.DOWNLOAD_ACTION:
                                if (mineTvDownloadController != null) {
                                    if (!mineTvDownloadController.isDelete()) {
                                        Bundle bundle = intent.getExtras();
                                        if (bundle != null) {
                                            DownProgramModel downProgramModel = bundle.getParcelable(DownloadConstant.EXTRA_INTENT_DOWNLOAD);
                                            if (downProgramModel != null) {
                                                mineTvDownloadController.updateDownProgram(downProgramModel);
                                            } else {
                                                mineTvDownloadController.updateDownProgram();
                                            }
                                        } else {
                                            mineTvDownloadController.updateDownProgram();
                                        }
                                    }
                                }
                                break;
                        }
                    }
                }
            };
            DownloadM3u8Controller.getInstance().registerDownloadReceiver(mContext, downloadReceiver);
        }
        return view;
    }

    public void hidePause() {
        ll_mine_pause.setVisibility(View.GONE);
        v_spilt_pause.setVisibility(View.GONE);
    }

    public void showPause() {
        ll_mine_pause.setVisibility(View.VISIBLE);
        v_spilt_pause.setVisibility(View.VISIBLE);
    }

    public void hideBottom() {
        v_spilt_bottom.setVisibility(View.GONE);
        ll_mine_bottom.setVisibility(View.GONE);
    }

    public void showBottom() {
        v_spilt_bottom.setVisibility(View.VISIBLE);
        ll_mine_bottom.setVisibility(View.VISIBLE);
    }

    @Override
    public void initData() {
        initListen();
        trl_mine.startRefresh();
    }

    private void initListen() {
        sub_segment_tab.setOnTabSelectListener(this);
        btn_all.setOnClickListener(this);
        all_text.setOnClickListener(this);
    }

    @Override
    protected void bindView() {
        index = getArguments().getInt(POSITION_KEY, 2);
        switch (index) {
            case MineFragment.POSITION_SUBSCRIPT:
                bindSubscription();
                break;
            case MineFragment.POSITION_APPOINT:
                bindAppoint();
                break;
            case MineFragment.POSITION_HISTORY:
                bindHistory();
                break;
            case MineFragment.POSITION_DOWNLOAD:
                bindDownload();
                break;
        }
    }

    /**
     *  刷新
     */
    RefreshListenerAdapter refreshListener = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(TwinklingRefreshLayout refreshLayout) {
            refresh();
        }

        @Override
        public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
            loadmore();
        }
    };

    private void refresh() {
        switch (index) {
            case MineFragment.POSITION_SUBSCRIPT:
                mineSubscriptionController.bindSubscriptData(currentSubTabSelect);
                break;
            case MineFragment.POSITION_APPOINT:
                mineAppointmentController.bindTvAppointData();
                break;
            case MineFragment.POSITION_HISTORY:
                mineTvHistroyController.bindTvHistroyData();
                break;
            case MineFragment.POSITION_DOWNLOAD:
                mineTvDownloadController.bindSubscriptData(new ValueCallback<Boolean>() {
                    @Override
                    public void onReceiveValue(Boolean value) {
                        if (value) {
                            btn_all.setImageResource(R.mipmap.mine_play_nor);
                            all_text.setText("全部开始");
                        } else {
                            btn_all.setImageResource(R.mipmap.mine_pause_nor);
                            all_text.setText("全部暂停");
                        }
                    }
                });
                break;
        }
    }

    private void loadmore() {

    }

    /**
     * 绑定订阅
     */
    private void bindSubscription() {
        hidePause();
        hideBottom();
        edit_mine_btn.setVisibility(View.GONE);
        sub_segment_tab.setVisibility(View.VISIBLE);
        sub_segment_tab.setTabData(subscriptionTitles);


        empty_image.setImageResource(R.mipmap.empty_subscribe);
        empty_text.setText("暂无订阅");

        rl_mine.removeItemDecoration(itemDecoration);

        trl_mine.setEnableRefresh(true);
        trl_mine.setEnableLoadmore(false);

        mineSubscriptionController = new MineSubscriptionController(mContext, this);
        mineSubscriptionController.init(rl_mine, loadView, trl_mine, notDataView);
    }


    /**
     * 绑定预约
     */
    private void bindAppoint() {
        hideBottom();
        hidePause();
        sub_segment_tab.setVisibility(View.GONE);
        edit_mine_btn.setVisibility(View.GONE);

        empty_image.setImageResource(R.mipmap.empty_order);
        empty_text.setText("暂无预约");

        rl_mine.removeItemDecoration(itemDecoration);

        trl_mine.setEnableRefresh(true);
        trl_mine.setEnableLoadmore(false);

        mineAppointmentController = new MineAppointmentController(mContext, this);
        mineAppointmentController.init(rl_mine, loadView, trl_mine, notDataView, edit_mine_btn);
        mineAppointmentController.setDeteleView(tv_mine_select);
    }

    /**
     * 绑定历史
     */
    private void bindHistory() {
        hidePause();
        hideBottom();
        sub_segment_tab.setVisibility(View.GONE);
        edit_mine_btn.setVisibility(View.GONE);

        empty_image.setImageResource(R.mipmap.empty_record);
        empty_text.setText("暂无观看记录");

        trl_mine.setEnableRefresh(true);
        trl_mine.setEnableLoadmore(false);

        rl_mine.addItemDecoration(itemDecoration);

        mineTvHistroyController = new MineTvHistroyController(mContext, this);
        mineTvHistroyController.init(rl_mine, loadView, trl_mine, notDataView, edit_mine_btn);
        mineTvHistroyController.setDeteleView(tv_mine_select);

    }

    /**
     * 绑定下载
     */
    private void bindDownload() {
        showPause();
        hideBottom();
        sub_segment_tab.setVisibility(View.VISIBLE);
        edit_mine_btn.setVisibility(View.GONE);
        sub_segment_tab.setTabData(downloadTitles);

        empty_image.setImageResource(R.mipmap.empty_download);
        empty_text.setText("暂无下载视频");

        trl_mine.setEnableRefresh(true);
        trl_mine.setEnableLoadmore(false);

        rl_mine.addItemDecoration(itemDecoration);
        mineTvDownloadController = new MineTvDownloadController(mContext, this);
        mineTvDownloadController.init(rl_mine, loadView, trl_mine, notDataView, ll_mine_pause, v_spilt_pause, edit_mine_btn);
        mineTvDownloadController.setDeteleView(tv_mine_select);
        mineTvDownloadController.setBtnView(btn_all, all_text);
    }

    @Override
    public void onTabSelect(int position) {
        switch (index) {
            case MineFragment.POSITION_SUBSCRIPT:
                currentSubTabSelect = position;
                mineSubscriptionController.setCurrentSelect(position);
                mineSubscriptionController.bindSubscriptData(position);
                break;
            case MineFragment.POSITION_DOWNLOAD:
                if (mineTvDownloadController.isDelete()) {
                    edit_mine_btn.setText("编辑");
                    hideBottom();
                    mineTvDownloadController.changeDelete();
                }
                if (mineTvDownloadController.isSelectAll()) {
                    tv_mine_select.setText("全选");
                    mineTvDownloadController.changeSelectAll();
                }
                mineTvDownloadController.setCurrentSelect(position);
                mineTvDownloadController.bindSubscriptData(position, new ValueCallback<Boolean>() {
                    @Override
                    public void onReceiveValue(Boolean value) {
                        if (mineTvDownloadController.isAllPause()) {
                            btn_all.setImageResource(R.mipmap.mine_play_nor);
                            all_text.setText("全部开始");
                        } else {
                            btn_all.setImageResource(R.mipmap.mine_pause_nor);
                            all_text.setText("全部暂停");
                        }
                    }
                });
                break;
        }
    }

    @Override
    public void onTabReselect(int position) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (downloadReceiver != null) {
            DownloadM3u8Controller.getInstance().unRegisterDownloadReceiver(mContext, downloadReceiver);
            downloadReceiver = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_mine_btn:
                switch (index) {
                    case MineFragment.POSITION_APPOINT:
                        if (mineAppointmentController != null) {
                            if (mineAppointmentController.isDelete()) {
                                edit_mine_btn.setText("编辑");
                                hideBottom();
                            } else {
                                edit_mine_btn.setText("取消");
                                showBottom();
                            }
                            mineAppointmentController.changeDelete();
                        }
                        break;
                    case MineFragment.POSITION_HISTORY:
                        if (mineTvHistroyController != null) {
                            if (mineTvHistroyController.isDelete()) {
                                edit_mine_btn.setText("编辑");
                                hideBottom();
                            } else {
                                edit_mine_btn.setText("取消");
                                showBottom();
                            }
                            mineTvHistroyController.changeDelete();
                        }
                        break;
                    case MineFragment.POSITION_DOWNLOAD:
                        if (mineTvDownloadController != null) {
                            if (mineTvDownloadController.isDelete()) {
                                btn_all.setClickable(true);
                                all_text.setClickable(true);
                                edit_mine_btn.setText("编辑");
                                hideBottom();
                            } else {
                                btn_all.setClickable(false);
                                all_text.setClickable(false);
                                edit_mine_btn.setText("取消");
                                showBottom();
                            }
                            mineTvDownloadController.changeDelete();
                        }
                        break;
                }
                break;
            case R.id.tv_mine_select:
                switch (index) {
                    case MineFragment.POSITION_APPOINT:
                        if (mineAppointmentController != null) {
                            if (mineAppointmentController.isSelectAll()) {
                                tv_mine_select.setText("全选");
                            } else {
                                tv_mine_select.setText("取消全选");
                            }
                            mineAppointmentController.changeSelectAll();
                        }
                        break;
                    case MineFragment.POSITION_HISTORY:
                        if (mineTvHistroyController != null) {
                            if (mineTvHistroyController.isSelectAll()) {
                                tv_mine_select.setText("全选");
                            } else {
                                tv_mine_select.setText("取消全选");
                            }
                            mineTvHistroyController.changeSelectAll();
                        }
                        break;
                    case MineFragment.POSITION_DOWNLOAD:
                        if (mineTvDownloadController != null) {
                            if (mineTvDownloadController.isSelectAll()) {
                                tv_mine_select.setText("全选");
                            } else {
                                tv_mine_select.setText("取消全选");
                            }
                            mineTvDownloadController.changeSelectAll();
                        }
                        break;
                }
                break;
            case R.id.tv_mine_delete:
                switch (index) {
                    case MineFragment.POSITION_APPOINT:
                        if (mineAppointmentController != null) {
                            mineAppointmentController.deleteSelect();
                        }
                        break;
                    case MineFragment.POSITION_HISTORY:
                        if (mineTvHistroyController != null) {
                            mineTvHistroyController.deleteSelect();
                        }
                        break;
                    case MineFragment.POSITION_DOWNLOAD:
                        if (mineTvDownloadController != null) {
                            mineTvDownloadController.deleteSelect();
                        }
                        break;
                }
                break;
            case R.id.btn_all:
            case R.id.all_text:
                switch (index) {
                    case MineFragment.POSITION_DOWNLOAD:
                        if (mineTvDownloadController != null) {
                            if (mineTvDownloadController.changePause()) {
//                                if (mineTvDownloadController.isAllPause()) {
//                                    btn_all.setImageResource(R.mipmap.mine_play_nor);
//                                    all_text.setText("全部开始");
//                                } else {
//                                    btn_all.setImageResource(R.mipmap.mine_pause_nor);
//                                    all_text.setText("全部暂停");
//                                }
                            }
                        }
                        break;
                }
                break;
        }
    }
}
